﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using MS.InformationManagement.Presenter.Support;
using MS.InformationManagement.Presenter.ShippingControlTemplates;
using MS.InformationManagement.DAL.DTOs;
using System.Collections.Generic;
using MS.InformationManagement.Core.TransactionsResponse;
using System.Linq;
using MS.InformationManagement.Support;
using MS.InformationManagement.DAL.DocumentCenter;

namespace MS.InformationManagement.WP.DocumentCenter.ShippingControlTemplates
{
    public partial class ShippingControlTemplatesUserControl : BaseControl, IShippingControlTemplatesView
    {

        #region fields
        ShippingControlTemplatesPresenter _presenter;

        #endregion

        #region Properties

        public string IdRadicado { get; set; }
        public IEnumerable<MotivosDeDevolucion> MotivosRechazo { get; set; }
        public DeliveryFormCreationResponse ShippingResponse { get; set; }
        public System.Collections.Generic.List<PlanillasDTO> foundRadicados
        {
            get
            {
                return ViewState["foundRadicados"] as System.Collections.Generic.List<DAL.DTOs.PlanillasDTO>;
            }
            set
            {
                ViewState["foundRadicados"] = value;
            }
        }


        #endregion

        #region Form Events

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            Page.RegisterAjaxLoaderPlugin();
            _presenter = new ShippingControlTemplatesPresenter(this);
            btnSearch.AddLoader();
            btnSubmitOperation.AddLoader();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                _presenter.HandleLoad();
                  if (gvRadicados.Rows.Count > 0)
                      btnSubmitOperation.Visible = true;
                  else
                      btnSubmitOperation.Visible = false;

            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            try
            {
                IdRadicado = txtBuscar.Text;
                _presenter.HandleSearch();
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }

        }

        protected void gvRadicados_RowCreated(object sender, GridViewRowEventArgs e)
        {

        }

        protected void gvRadicados_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType != DataControlRowType.EmptyDataRow)
            {
                e.Row.Cells[0].Visible = false;
            }
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                DropDownList ddl = (DropDownList)e.Row.FindControl("ddlMotivos");
                ddl.DataSource = MotivosRechazo;
                ddl.DataTextField = "Title";
                ddl.DataValueField = "Id";
                ddl.DataBind();
            }
        }

        protected void chk_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                CheckBox chkBx = (CheckBox)sender;
                GridViewRow row = chkBx.NamingContainer as GridViewRow;
                DropDownList ddl = (DropDownList)row.FindControl("ddlMotivos");
                if (chkBx.Checked)
                    ddl.Enabled = true;
                else
                    ddl.Enabled = false;
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        void chkSelect_CheckedChanged(object sender, EventArgs e)
        {
           
        }

        protected void btnSubmitOperation_Click(object sender, EventArgs e)
        {
            try
            {
                if (gvRadicados.Rows.Count > 0)
                {
                    foreach (GridViewRow row in gvRadicados.Rows)
                    {
                        DropDownList ddl = (DropDownList)row.FindControl("ddlMotivos");
                        CheckBox chkSelect = (CheckBox)row.FindControl("chk");
                        if (foundRadicados != null && chkSelect != null)
                        {
                            var element = (from item in foundRadicados
                                           where item.IdItemMedioEnvio == int.Parse(row.Cells[0].Text)
                                           select item).FirstOrDefault();

                            if (element != null)
                            {
                                element.Recibido = !chkSelect.Checked;
                                if (chkSelect.Checked)
                                {
                                    MotivosDeDevolucion motivoRechazo = MotivosRechazo.Where(x => x.Id == int.Parse(ddl.SelectedItem.Value)).FirstOrDefault();
                                    element.MotivoRechazo = motivoRechazo.Title;
                                    element.Reprogrmar = motivoRechazo.Reprogrmar.Value;
                                }
                                else
                                    element.Reprogrmar = false;
                            }
                        }
                    }
                    _presenter.UpdateStatusShipping();
                    gvRadicados.DataBind();
                    btnSubmitOperation.Visible = false;
                }
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        #endregion

        #region Implemented Methods

        public void Show()
        {
            //LoadGridView();
        }

        public void ShowSearch()
        {
            LoadGridView();
        }        

        public void ShowMessage()
        {
            if (ShippingResponse.Result == true)
            {
                this._ShowAlertAndClose("Operación ejecutada exitosamente");
            }
            else 
            {
                this._ShowAlertAndClose("Ha ocurrido un problema durante la operación");
            }
        }

        #endregion

        #region Private Methods
        
        private void LoadGridView()
        {
            try
            {
                if (foundRadicados.Count == 0)
                    btnSubmitOperation.Visible = false;
                else if (MotivosRechazo == null || MotivosRechazo.Count() == 0)
                {
                    btnSubmitOperation.Visible = false;
                    this.HandleWarning("No existen motivos de rechazo de envíos cargados en el sistema");
                }
                else
                {
                    gvRadicados.DataSource = foundRadicados;
                    gvRadicados.DataBind();
                    btnSubmitOperation.Visible = true;
                }
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        #endregion

        

    }
}
